import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import { AUTH_TOKEN } from "./contants";
import { currentOrg } from ".";

// 由于每次发送请求都要携带token，所以统一配置

const httpLink = createHttpLink({
  uri: "//localhost:3000/graphql",
});

const authLink = setContext((_, { headers }) => {
  const token =
    sessionStorage.getItem(AUTH_TOKEN) || localStorage.getItem(AUTH_TOKEN);
  return {
    headers: {
      ...headers,
      Authorization: token ? `Bearer ${token}` : "",
      orgId: currentOrg()?.value
    },
  };
});

export const client = new ApolloClient({
  // uri:'http://localhost:3000/graphql',
  // uri:'http://localhost:8888/graphql', // 在使用pnpm run mock 验证完之后，就可以在这里把后端接口改成mock接口
  link: authLink.concat(httpLink),
  cache: new InMemoryCache({
    addTypename: false,
  }),
});
